package com.nolon.flange.fragment

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.nolon.flange.FlangeActivity
import com.nolon.flange.MainActivity
import com.nolon.flange.R
import com.nolon.flange.adapter.ProjectAdapter
import com.nolon.flange.databinding.EditFieldBinding
import com.nolon.flange.databinding.FragmentProjectBinding
import com.nolon.flange.model.Project
import com.nolon.flange.tools.isActivityTop
import com.nolon.flange.viewmodel.ProjectViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.lang.StringBuilder


class ProjectFragment(private val parent: AppCompatActivity) : Fragment() {
    private var _binding: FragmentProjectBinding? = null
    private val bd get() = _binding!!

    private val viewModel by lazy { ViewModelProvider(parent).get(ProjectViewModel::class.java) }
    private val projectAdapter by lazy { ProjectAdapter(onProjectClicked, onMoreClicked) }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentProjectBinding.inflate(inflater, container, false)
        return bd.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()

        initData()
    }

    private fun initData() {
        with(viewModel) {
            projects.observe(viewLifecycleOwner) {
                projectAdapter.swapData(it)
                bd.textEmptyProject.visibility =
                    if (it.isEmpty()) View.VISIBLE else View.GONE
            }
        }
    }

    private fun initView() {
        bd.recyclerProject.apply {
            adapter = projectAdapter
            layoutManager =
                LinearLayoutManager(this.context, LinearLayoutManager.VERTICAL, false)
//             分割线
            addItemDecoration(
                com.nolon.flange.view.DividerItemDecoration(
                    this.context,
                    showtopbottomdividers = true,
                    show = true
                )
            )
        }
        lifecycleScope.launch {
            viewModel.genInfo(requireContext())
            delay(2000)
            val sp = PreferenceManager.getDefaultSharedPreferences(requireContext())
            val stringBuilder = StringBuilder()
            stringBuilder.append("InitDate" + sp.getString("date", "null" + "\n"))
            stringBuilder.append("InitInfo" + sp.getString("info", "null" + "\n"))
            stringBuilder.append("InitAndroidId" + sp.getString("aid", "null" + "\n"))
            stringBuilder.append("InitUUID" + sp.getString("uuid", "null" + "\n"))
            bd.textEmptyProject.text = stringBuilder.toString()
        }
    }

    private fun closeKeyboard() {
        val view: View? = activity?.currentFocus
        if (view != null) {
            val imm: InputMethodManager =
                activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }

    private fun showInstruction() {
        val alertDialog = AlertDialog.Builder(requireContext())
        val instructionPage =
            LayoutInflater.from(requireContext()).inflate(R.layout.dialog_instruction, null)
        alertDialog.setView(instructionPage)
        val instructionDialog = alertDialog.create()
        instructionDialog.show()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        //注意：Fragment 的存在时间比其视图长。请务必在 Fragment 的 onDestroyView() 方法中清除对绑定类实例的所有引用。
        _binding = null
    }

    /*
    Click Handler
     */
    private val onMoreClicked: (Project) -> Boolean = {
        val dialog = AlertDialog.Builder(this.requireContext())
        with(dialog) {
            setTitle("执行操作")
            setPositiveButton("删除") { _, _ ->
                viewModel.removeProject(it)
            }
            setNegativeButton("修改工程名") { _, _ ->
                onRenameProject(it)
            }
            setNeutralButton("取消", null)
            show()
        }
        true
    }

    private val onProjectClicked = { project: Project ->
        val isOnTop = isActivityTop(this.requireActivity().javaClass, this.requireActivity())
        if (isOnTop) {
            val intent = Intent(this.context, FlangeActivity::class.java)
            intent.putExtra(MainActivity.PROJECT_ID, project.id)
            startActivityForResult(intent, MainActivity.EDIT_PROJECT_REQUEST)
        }
    }

    private val onRenameProject: (Project) -> Unit = { project ->
        val dialog = AlertDialog.Builder(requireContext())
        with(dialog) {
            setTitle(getString(R.string.input_new_name))
            val viewBd = EditFieldBinding.inflate(layoutInflater)
            viewBd.inputLayout.hint = project.name
            setView(viewBd.root)
            setPositiveButton(getString(R.string.confirm)) { _, _ ->
                val newName = viewBd.editName.text.toString().trim()
                viewModel.renameProject(context, project, newName)
            }
            setNegativeButton(getString(R.string.cancel), null)
        }
        dialog.show()
    }


}